package OT.shoufouni.gpsMaps;

import java.util.ArrayList;

import org.andnav.osm.ResourceProxy;
import org.andnav.osm.util.GeoPoint;
import org.andnav.osm.views.OpenStreetMapView;
import org.andnav.osm.views.overlay.MyLocationOverlay;
import org.andnav.osm.views.overlay.OpenStreetMapViewOverlayItem;
import org.andnav.osm.views.util.Mercator;
import org.andnav.osm.views.util.OpenStreetMapRendererInfo;


import OT.shoufouni.mainGUI.myLocation;
import OT.shoufouni.serverThreads.serverRouteQuaryThread;
import OT.shoufouni.serverThreads.serverUpdateFriendLocationQuaryThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

public class findRoute extends Activity
{
	
	public OpenStreetMapView mOSMap;
	public MyLocationOverlay mLocationOverlay;
	public routeLocation route;
   
	public newItemizedOverlay<OpenStreetMapViewOverlayItem> mStationOverlay;
	public ArrayList<OpenStreetMapViewOverlayItem> stations;
	
	public static GeoPoint gPoint = null;
	public static Resources res;
	ResourceProxy mResourceProxy;
	
	private Handler mHandler = new Handler();
	
	public static final String ID_MAIL= "ID_MAIL";
    SharedPreferences prefs;
	String IdMail;
	
	public OpenStreetMapView getView(){
		return mOSMap; 
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
       
      //Capturing all of the screen
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);
       
      //create the layout that you will use.
        RelativeLayout mLayout = new RelativeLayout(this);
      //create the map view that you will use. 
        mOSMap = new OpenStreetMapView(this.getApplicationContext(), OpenStreetMapRendererInfo.values()[OpenStreetMapRendererInfo.MAPNIK.ordinal()]);
      //set built in zoom handles.  
        mOSMap.setBuiltInZoomControls(true);
      //set multi-touch to true.
        mOSMap.setMultiTouchControls(true);
      //init your resource proxy (the file you created earlier).
        mResourceProxy = new ResourceProxyImpl(getApplicationContext());  
        
      //grab your application's resources to use your drawables (in this case).
        res = this.getResources();
      //create an ArrayList of stations.
        stations = new ArrayList<OpenStreetMapViewOverlayItem>();
        
      //create a layer that will track the device's location.
        mLocationOverlay = new MyLocationOverlay(this.getBaseContext(), mOSMap, mResourceProxy);
      
        
        GeoPoint dest,current = null;
        current = mLocationOverlay.getMyLocation();
        if (null == current){
        	// fake checking value
            current = new GeoPoint(32.08672,34.789774);
        }
        setMapCenter(current);
        
        Context context = getApplicationContext();
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
        IdMail = prefs.getString(ID_MAIL, "");
        
        stations.add(new OpenStreetMapViewOverlayItem("Here i am!",IdMail, current));
        
        // get the dest point
        Double extraMsg1 = null;
        Double extraMsg2 = null;
        if (null!= getIntent().getExtras()){
        	extraMsg1 =	getIntent().getExtras().getDouble("locationX");
        	extraMsg2 = getIntent().getExtras().getDouble("locationY");
        	dest = new GeoPoint(extraMsg1,extraMsg2);
     
        	// get the route from the server
        	Thread routeServer = new serverRouteQuaryThread(this,this, mOSMap, current, dest);
        	routeServer.start();
        	// keep updating the friend location
        	serverUpdateFriendLocationQuaryThread myFriendLocationUpdate = new serverUpdateFriendLocationQuaryThread(this,getIntent().getExtras().getString("adress"),IdMail);
            myFriendLocationUpdate.start();
	        
        	if (null!=extraMsg1){
	        	Log.d("from",current.toString()+" "+current.toString());
	        	Log.d("to ", dest.toString()+" "+dest.toString());
	        	stations.add(new OpenStreetMapViewOverlayItem(getIntent().getExtras().getString("name"),getIntent().getExtras().getString("adress"), dest));
	        }
        }
          //create the overlay with the stations you created earlier and a marker base for the stations (i chose the android icon - very original, i know :)
          mStationOverlay = new newItemizedOverlay<OpenStreetMapViewOverlayItem>
          (
          		this, 
          		stations, 
          		this.getResources().getDrawable(OT.shoufouni.R.drawable.androidmarker), 
          		null, 
          		this.getResources().getDrawable(OT.shoufouni.R.drawable.androidmarker), 
          		null, 
          		0, 
          		null, 
          		mResourceProxy
          );
          
          mOSMap.getOverlays().add(mStationOverlay);
        
        //add the layer you created to the map's layers.
          mOSMap.getOverlays().add(mLocationOverlay);
      //add the map to the layout while telling it to grab the whole screen.
        mLayout.addView(mOSMap, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
      //set the layout you created as the content view (what is visible since the creation of the activity).
        this.setContentView(mLayout);
        //set zoom (the number was chosen randomlly to get you acquainted with this feature).
        mOSMap.getController().setZoom(12);
      
        //set center of map to your location(or to 32.06982,34.844191 if the gps isn't on or functioning). 
        setMapCenter(mLocationOverlay.getMyLocation());    
    }
 // sets the map center to a given point or to 32.08672,34.789774
    public void setMapCenter(GeoPoint geoPoint)
    {
    	final org.andnav.osm.util.Point p;
    	
    	if(geoPoint != null)
    		p = Mercator.projectGeoPoint(geoPoint, this.getPixelZoomLevel(), null);
    	else
    	{
    		gPoint = new GeoPoint(32.06982,34.844191);
    		p = Mercator.projectGeoPoint(gPoint, this.getPixelZoomLevel(), null);
    	}
    	
		final int worldSize_2 = this.getWorldSizePx()/2;
		mOSMap.scrollTo(p.x - worldSize_2, p.y - worldSize_2);
    }
   
    int getWorldSizePx() {
       return (1 << getPixelZoomLevel());
   }

/**
     * Get the equivalent zoom level on pixel scale
     */
    int getPixelZoomLevel() {
      return mOSMap.getZoomLevel() + mOSMap.getRenderer().MAPTILE_ZOOM;
  }
   
    @Override
    public void onPause()
    {
      //this feature is turned off when the activity is paused to save battery life.
     mLocationOverlay.disableMyLocation();
      super.onPause();
    }
   
    public void onResume()
    {
      super.onResume();
      mOSMap.setRenderer(OpenStreetMapRendererInfo.values()[OpenStreetMapRendererInfo.MAPNIK.ordinal()]);
        mLocationOverlay.enableMyLocation();
       mLocationOverlay.followLocation(true);
    }
    
    @Override
  public void onRestart()
    {          
       super.onRestart();
}
   
@Override
  public void onStop(){
      super.onStop();
    }
 
   @Override
  public void onDestroy(){
      super.onDestroy();
}
 
   @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
      //Handle the back button
   if (keyCode == KeyEvent.KEYCODE_BACK) {
      //Ask the user if they want to quit
        new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
       .setTitle("Exit")
        .setMessage("Are you sure you want to leave?")
       .setNegativeButton(android.R.string.cancel, null)
          .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which){
              // Exit the activity
        	  findRoute.this.finish();
           }
        })
         .show();

        // Say that we've consumed the event
      return true;
     }

     return super.onKeyDown(keyCode, event);
  }
   
   public void responseDisplay(final routeLocation location) {
   	mHandler.post(new Runnable() {
           public void run() {
           	if (null==location){
           		Toast.makeText(findRoute.this,"Connecting failed or couldn't locate the friend"+"\nPlease try again",Toast.LENGTH_LONG).show();
           	}
           	else{
           		mOSMap.getOverlays().add(location);
           	}
            }
         });
   }
   // update the locations
   public void responseDisplayFriendLocation(final myLocation location) {
	   	mHandler.post(new Runnable() {
	           public void run() {
	           	if (null==location){
	           		Toast.makeText(findRoute.this,"Connecting failed or couldn't locate the friend"+"\nPlease try again",Toast.LENGTH_LONG).show();
	           	}
	           	else{
	           		// remove the last friend locations
	           		mOSMap.getOverlays().remove(0);
	           		stations.clear();
	           		GeoPoint current = null;
	           		current = mLocationOverlay.getMyLocation();
	           		if (null == current){
	                	// fake location value
	                    current = new GeoPoint(32.08672,34.789774);
	                }
	           		stations.add(new OpenStreetMapViewOverlayItem("Here i am!",IdMail, current));
		        	stations.add(new OpenStreetMapViewOverlayItem(
		        			getIntent().getExtras().getString("name"),
		        			getIntent().getExtras().getString("adress"),
		        			new GeoPoint(location.getX(),location.getY())));
		        	mStationOverlay = new newItemizedOverlay<OpenStreetMapViewOverlayItem>
		            (
		            		findRoute.this, 
		            		stations, 
		            		findRoute.this.getResources().getDrawable(OT.shoufouni.R.drawable.androidmarker), 
		            		null, 
		            		findRoute.this.getResources().getDrawable(OT.shoufouni.R.drawable.androidmarker), 
		            		null, 
		            		0, 
		            		null, 
		            		mResourceProxy
		            );
		            
		            mOSMap.getOverlays().add(0,mLocationOverlay);
	           	}
	            }
	         });
	   }
}

